<template>
  <div class="workload-ranking-container">
    <!-- 筛选条件 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="filterForm" :inline="true" label-width="80px">
        <el-form-item label="统计周期">
          <el-select v-model="filterForm.period" placeholder="请选择统计周期">
            <el-option label="本周" value="week" />
            <el-option label="本月" value="month" />
            <el-option label="本季度" value="quarter" />
            <el-option label="自定义" value="custom" />
          </el-select>
        </el-form-item>
        
        <el-form-item v-if="filterForm.period === 'custom'" label="时间范围">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        
        <el-form-item label="分公司">
          <el-select v-model="filterForm.companyId" placeholder="请选择分公司" clearable>
            <el-option label="全部" value="" />
            <el-option
              v-for="company in companyList"
              :key="company.id"
              :label="company.name"
              :value="company.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="工作类型">
          <el-select v-model="filterForm.workType" placeholder="请选择工作类型" clearable>
            <el-option label="全部" value="" />
            <el-option label="客户拜访" value="visit" />
            <el-option label="电话沟通" value="call" />
            <el-option label="合同签署" value="contract" />
            <el-option label="售后服务" value="service" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleFilter" :loading="loading">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 工作量概览 -->
    <el-row :gutter="20" class="overview-row">
      <el-col :span="4">
        <el-card class="overview-card">
          <div class="overview-item">
            <div class="overview-icon total">
              <el-icon><DataAnalysis /></el-icon>
            </div>
            <div class="overview-content">
              <div class="overview-value">{{ overviewData.totalWorkload }}</div>
              <div class="overview-label">总工作量</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="overview-card">
          <div class="overview-item">
            <div class="overview-icon visit">
              <el-icon><Position /></el-icon>
            </div>
            <div class="overview-content">
              <div class="overview-value">{{ overviewData.totalVisits }}</div>
              <div class="overview-label">客户拜访</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="overview-card">
          <div class="overview-item">
            <div class="overview-icon call">
              <el-icon><Phone /></el-icon>
            </div>
            <div class="overview-content">
              <div class="overview-value">{{ overviewData.totalCalls }}</div>
              <div class="overview-label">电话沟通</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="overview-card">
          <div class="overview-item">
            <div class="overview-icon contract">
              <el-icon><Document /></el-icon>
            </div>
            <div class="overview-content">
              <div class="overview-value">{{ overviewData.totalContracts }}</div>
              <div class="overview-label">合同签署</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="overview-card">
          <div class="overview-item">
            <div class="overview-icon service">
              <el-icon><Tools /></el-icon>
            </div>
            <div class="overview-content">
              <div class="overview-value">{{ overviewData.totalServices }}</div>
              <div class="overview-label">售后服务</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="overview-card">
          <div class="overview-item">
            <div class="overview-icon avg">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="overview-content">
              <div class="overview-value">{{ overviewData.avgWorkload }}</div>
              <div class="overview-label">人均工作量</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表分析 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card" shadow="never">
          <template #header>
            <span>工作量趋势分析</span>
          </template>
          <div ref="trendChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card class="chart-card" shadow="never">
          <template #header>
            <span>工作类型分布</span>
          </template>
          <div ref="typeChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 工作量排行榜 -->
    <el-card class="table-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>工作量排行榜</span>
          <div class="header-actions">
            <el-button type="success" size="small" @click="handleExport">
              <el-icon><Download /></el-icon>
              导出排行榜
            </el-button>
            <el-button type="warning" size="small" @click="handleWorkloadAnalysis">
              <el-icon><DataAnalysis /></el-icon>
              工作量分析
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        style="width: 100%"
        :row-class-name="getRowClassName"
      >
        <el-table-column label="排名" width="80" align="center">
          <template #default="{ $index }">
            <div class="rank-cell">
              <el-icon v-if="$index < 3" class="rank-icon" :class="getRankIconClass($index)">
                <Trophy />
              </el-icon>
              <span v-else class="rank-number">{{ $index + 1 }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="业务员" width="150">
          <template #default="{ row }">
            <div class="salesman-cell">
              <el-avatar :size="32" :src="row.avatar">
                {{ row.salesmanName?.charAt(0) }}
              </el-avatar>
              <span class="salesman-name">{{ row.salesmanName }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="companyName" label="分公司" width="120" />
        <el-table-column prop="totalWorkload" label="总工作量" width="120" align="center">
          <template #default="{ row }">
            <span class="workload-total">{{ row.totalWorkload }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="visitCount" label="客户拜访" width="100" align="center">
          <template #default="{ row }">
            <span class="visit-count">{{ row.visitCount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="callCount" label="电话沟通" width="100" align="center">
          <template #default="{ row }">
            <span class="call-count">{{ row.callCount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="contractCount" label="合同签署" width="100" align="center">
          <template #default="{ row }">
            <span class="contract-count">{{ row.contractCount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="serviceCount" label="售后服务" width="100" align="center">
          <template #default="{ row }">
            <span class="service-count">{{ row.serviceCount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="workingDays" label="工作天数" width="100" align="center" />
        <el-table-column prop="avgDailyWorkload" label="日均工作量" width="120" align="center">
          <template #default="{ row }">
            <span class="avg-workload">{{ row.avgDailyWorkload?.toFixed(1) || '0.0' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="efficiency" label="工作效率" width="100" align="center">
          <template #default="{ row }">
            <el-progress
              :percentage="row.efficiency"
              :color="getEfficiencyColor(row.efficiency)"
              :stroke-width="8"
              text-inside
            />
          </template>
        </el-table-column>
        <el-table-column prop="lastWorkDate" label="最近工作" width="120" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleViewDetail(row)">
              详情
            </el-button>
            <el-button type="success" size="small" @click="handleViewReport(row)">
              报告
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Search, 
  Refresh, 
  Download, 
  DataAnalysis, 
  Position, 
  Phone, 
  Document, 
  Tools, 
  TrendCharts,
  Trophy
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'

// 响应式数据
const loading = ref(false)
const trendChartRef = ref<HTMLDivElement>()
const typeChartRef = ref<HTMLDivElement>()

// 筛选表单
const filterForm = reactive({
  period: 'month',
  dateRange: [],
  companyId: '',
  workType: ''
})

// 分页数据
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 概览数据
const overviewData = reactive({
  totalWorkload: 0,
  totalVisits: 0,
  totalCalls: 0,
  totalContracts: 0,
  totalServices: 0,
  avgWorkload: 0
})

// 表格数据
const tableData = ref([])

// 下拉选项
const companyList = ref([])

// 图表实例
let trendChart: echarts.ECharts | null = null
let typeChart: echarts.ECharts | null = null

// 方法
const handleFilter = () => {
  pagination.page = 1
  getTableData()
  updateCharts()
}

const handleReset = () => {
  Object.assign(filterForm, {
    period: 'month',
    dateRange: [],
    companyId: '',
    workType: ''
  })
  handleFilter()
}

const handleExport = () => {
  ElMessage.success('导出功能开发中')
}

const handleWorkloadAnalysis = () => {
  ElMessage.info('工作量分析功能开发中')
}

const handleViewDetail = (row: any) => {
  ElMessage.info(`查看 ${row.salesmanName} 的工作详情`)
}

const handleViewReport = (row: any) => {
  ElMessage.info(`查看 ${row.salesmanName} 的工作报告`)
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  getTableData()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  getTableData()
}

const getTableData = async () => {
  loading.value = true
  try {
    // TODO: 调用API获取数据
    setTimeout(() => {
      tableData.value = [
        {
          salesmanName: '张三',
          companyName: '北京分公司',
          totalWorkload: 156,
          visitCount: 45,
          callCount: 68,
          contractCount: 25,
          serviceCount: 18,
          workingDays: 22,
          avgDailyWorkload: 7.1,
          efficiency: 92,
          lastWorkDate: '2024-01-15',
          avatar: ''
        },
        {
          salesmanName: '李四',
          companyName: '上海分公司',
          totalWorkload: 142,
          visitCount: 38,
          callCount: 62,
          contractCount: 22,
          serviceCount: 20,
          workingDays: 21,
          avgDailyWorkload: 6.8,
          efficiency: 88,
          lastWorkDate: '2024-01-14',
          avatar: ''
        },
        {
          salesmanName: '王五',
          companyName: '广州分公司',
          totalWorkload: 128,
          visitCount: 35,
          callCount: 55,
          contractCount: 20,
          serviceCount: 18,
          workingDays: 20,
          avgDailyWorkload: 6.4,
          efficiency: 85,
          lastWorkDate: '2024-01-13',
          avatar: ''
        }
      ]
      pagination.total = 100
      
      // 更新概览数据
      Object.assign(overviewData, {
        totalWorkload: 3250,
        totalVisits: 980,
        totalCalls: 1520,
        totalContracts: 420,
        totalServices: 330,
        avgWorkload: 65
      })
      
      loading.value = false
    }, 1000)
  } catch (error) {
    loading.value = false
    ElMessage.error('获取数据失败')
  }
}

const initCharts = () => {
  nextTick(() => {
    if (trendChartRef.value) {
      trendChart = echarts.init(trendChartRef.value)
    }
    if (typeChartRef.value) {
      typeChart = echarts.init(typeChartRef.value)
    }
    updateCharts()
  })
}

const updateCharts = () => {
  updateTrendChart()
  updateTypeChart()
}

const updateTrendChart = () => {
  if (!trendChart) return
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['客户拜访', '电话沟通', '合同签署', '售后服务']
    },
    xAxis: {
      type: 'category',
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    },
    yAxis: {
      type: 'value',
      name: '工作量'
    },
    series: [
      {
        name: '客户拜访',
        type: 'line',
        stack: 'Total',
        data: [12, 15, 18, 20, 16, 8, 10],
        smooth: true
      },
      {
        name: '电话沟通',
        type: 'line',
        stack: 'Total',
        data: [25, 28, 32, 35, 30, 15, 20],
        smooth: true
      },
      {
        name: '合同签署',
        type: 'line',
        stack: 'Total',
        data: [8, 10, 12, 15, 12, 5, 8],
        smooth: true
      },
      {
        name: '售后服务',
        type: 'line',
        stack: 'Total',
        data: [6, 8, 10, 12, 10, 4, 6],
        smooth: true
      }
    ]
  }
  trendChart.setOption(option)
}

const updateTypeChart = () => {
  if (!typeChart) return
  
  const data = [
    { name: '客户拜访', value: 980 },
    { name: '电话沟通', value: 1520 },
    { name: '合同签署', value: 420 },
    { name: '售后服务', value: 330 }
  ]
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}次 ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '工作类型',
        type: 'pie',
        radius: ['40%', '70%'],
        data: data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  typeChart.setOption(option)
}

// 工具方法
const getRowClassName = ({ rowIndex }: { rowIndex: number }) => {
  if (rowIndex === 0) return 'first-place-row'
  if (rowIndex === 1) return 'second-place-row'
  if (rowIndex === 2) return 'third-place-row'
  return ''
}

const getRankIconClass = (index: number) => {
  const classes = ['gold-medal', 'silver-medal', 'bronze-medal']
  return classes[index] || ''
}

const getEfficiencyColor = (efficiency: number) => {
  if (efficiency >= 90) return '#67c23a'
  if (efficiency >= 80) return '#e6a23c'
  if (efficiency >= 70) return '#f56c6c'
  return '#909399'
}

// 初始化数据
const initData = () => {
  companyList.value = [
    { id: '1', name: '北京分公司' },
    { id: '2', name: '上海分公司' },
    { id: '3', name: '广州分公司' },
    { id: '4', name: '深圳分公司' },
    { id: '5', name: '杭州分公司' }
  ]
  
  getTableData()
  initCharts()
}

onMounted(() => {
  initData()
})
</script>

<style lang="scss" scoped>
.workload-ranking-container {
  padding: 20px;
  
  .filter-card {
    margin-bottom: 20px;
  }
  
  .overview-row {
    margin-bottom: 20px;
    
    .overview-card {
      .overview-item {
        display: flex;
        align-items: center;
        
        .overview-icon {
          width: 50px;
          height: 50px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 12px;
          font-size: 20px;
          color: white;
          
          &.total {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          }
          
          &.visit {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
          }
          
          &.call {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
          }
          
          &.contract {
            background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
          }
          
          &.service {
            background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
          }
          
          &.avg {
            background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
          }
        }
        
        .overview-content {
          .overview-value {
            font-size: 20px;
            font-weight: bold;
            color: #303133;
            margin-bottom: 3px;
          }
          
          .overview-label {
            font-size: 12px;
            color: #909399;
          }
        }
      }
    }
  }
  
  .chart-row {
    margin-bottom: 20px;
    
    .chart-card {
      .chart-container {
        height: 300px;
      }
    }
  }
  
  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-actions {
        display: flex;
        gap: 10px;
      }
    }
    
    .rank-cell {
      display: flex;
      align-items: center;
      justify-content: center;
      
      .rank-icon {
        font-size: 24px;
        
        &.gold-medal {
          color: #ffd700;
        }
        
        &.silver-medal {
          color: #c0c0c0;
        }
        
        &.bronze-medal {
          color: #cd7f32;
        }
      }
      
      .rank-number {
        font-size: 16px;
        font-weight: bold;
      }
    }
    
    .salesman-cell {
      display: flex;
      align-items: center;
      
      .salesman-name {
        margin-left: 10px;
      }
    }
    
    .workload-total {
      color: #409eff;
      font-weight: bold;
      font-size: 16px;
    }
    
    .visit-count {
      color: #67c23a;
      font-weight: bold;
    }
    
    .call-count {
      color: #e6a23c;
      font-weight: bold;
    }
    
    .contract-count {
      color: #f56c6c;
      font-weight: bold;
    }
    
    .service-count {
      color: #909399;
      font-weight: bold;
    }
    
    .avg-workload {
      color: #606266;
      font-weight: bold;
    }
    
    .pagination-container {
      margin-top: 20px;
      text-align: right;
    }
  }
}

// 表格行样式
:deep(.first-place-row) {
  background-color: rgba(255, 215, 0, 0.1) !important;
}

:deep(.second-place-row) {
  background-color: rgba(192, 192, 192, 0.1) !important;
}

:deep(.third-place-row) {
  background-color: rgba(205, 127, 50, 0.1) !important;
}
</style>
